// pages/info/info.js
const {
  getObjects,
  getObjectsByTypeID,
  createObject,
  createComment,
} = require("../../utils/apis");

Page({
  options: {
    styleIsolation: "shared",
  },
  options: {
    styleIsolation: "shared",
  },
  /**
   * 页面的初始数据
   */
  data: {
    teachers: {
      array: [],
      index: 0,
    },
    orgs: {
      index: 0,
      array: [],
      idArray: [],
    },
    columns: ["人物", "课程", "组织", "抽象"],
    vs: 0,
    showCreatPop: false,
    showPop: false, // 点评弹出层
    showSearch: true,
    lastScrollTop: 0, // 记录上一次滚动的位置
    requestPage: {
      page: 1,
      size: 6,
    },
    reviewList: [],
  },
  /**
   * 搜索栏关键字保存入查询req
   * @param {*} e
   */
  onChange(e) {
    this.setData({
      "requestPage.key": e.detail,
    });
  },
  /**
   * 取消搜索
   *
   */
  onCancel() {
    this.setData({
      reviewList: [],
      "requestPage.page": 1,
    });
    this.onSearch();
  },
  /**
   * TODO
   * 照片预览
   * @param {*} event
   */
  previewImage(event) {
    const reviewIndex = event.currentTarget.dataset.parentIndex;
    const index = event.currentTarget.dataset.childIndex;
    var photo = this.data.reviewList[reviewIndex].imagesList;
    wx.previewImage({
      current: photo[index],
      urls: photo,
    });
  },
  onSearchKey: function () {
    this.setData({
      reviewList: [],
      "requestPage.page": 1,
    });
    this.onSearch();
  },
  /**
   * 搜索
   * 向服务器发送查询信息
   */
  onSearch: function () {
    getObjects(this.data.requestPage.page, this.data.requestPage.size).then(
      (res) => {
        var newData = res.data.data;
        newData = this.timeDifference(newData);
        newData = this.addNewData(newData);
        newData = this.addSth(newData);
        if (res.data.data.length > 0) {
          this.newPage();
        }
        this.setData({
          reviewList: newData,
        });
      }
    );
  },
  newComment(e) {
    const formData = e.detail.value;
    if (this.data.writeObj.type === 2) {
      createComment({
        content: formData.content,
        score: formData.score,
        edges: {
          object: {
            id: this.data.writeObj.id,
          },
          course_comment: {
            difficulty: formData.difficulty,
            quality: formData.quality,
            workload: formData.workload,
            mark: formData.mark,
          },
        },
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      createComment({
        content: formData.content,
        score: formData.score,
        edges: {
          object: {
            id: this.data.writeObj.id,
          },
        },
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    }
    this.onClose();
    this.onShow();
  },
  /**
   * 计算每一天信息的更新时间与当前时间的差值并保存
   * @param {*} data
   */
  timeDifference: function (data) {
    // 遍历新数据，获取 updateTime 并计算差值
    data.forEach((item) => {
      const currentTime = new Date();
      const updateTime = new Date(item.updated_at * 1000);
      const timeDifference =
        (currentTime.getTime() - updateTime.getTime()) / (1000 * 60); // 计算时间差，单位为分钟
      item.timeDifference = timeDifference; // 将计算得到的时间差存储在数据对象中
    });
    return data;
  },
  /**
   * 向原数组中添加新数据，如果有数据id重合，则替换掉旧数据
   */
  addNewData: function (newData) {
    // 创建一个新的数组来存储替换后的数据
    const updatedReviewList = this.data.reviewList.map((oldItem) => {
      // 在新数据中查找与当前旧数据项相匹配的项
      const matchingNewItem = newData.find(
        (newItem) => newItem.id === oldItem.id
      );
      // 如果找到了匹配的项，则返回新数据项；否则返回旧数据项
      return matchingNewItem ? matchingNewItem : oldItem;
    });
    // 在新数据中过滤出没有匹配到的项
    const nonMatchingNewData = newData.filter(
      (newItem) => !updatedReviewList.some((item) => item.id === newItem.id)
    );
    // 将没有匹配到的新数据添加到替换后的数据列表的末尾
    updatedReviewList.push(...nonMatchingNewData);
    return updatedReviewList;
  },
  addSth: function (data) {
    //  计算评分
    data.forEach((item) => {
      var sum = 0;
      var count = 0;
      for (var key in item.edges.comments) {
        sum += item.edges.comments[key].score;
        count++;
      }
      item.score = (sum / count).toFixed(1);
    });
    data.forEach((item) => {
      // 计算评论数量
      if (item.edges.comments) {
        item.comments_num = item.edges.comments.length;
      } else {
        item.comments_num = 0;
      }
    });
    return data;
  },
  /**
   * 查询页+1
   */
  newPage: function () {
    const newPage = this.data.requestPage.page + 1;
    this.setData({
      "requestPage.page": newPage,
    });
  },
  /**
   * 页面滚动事件监听
   * @param {*} e
   */
  onPageScroll: function (e) {
    // 判断页面滚动位置是否达到你设定的触发上拉事件的条件
    if (e.scrollTop > this.data.lastScrollTop) {
      // 处理下拉事件的逻辑
      this.setData({
        showSearch: false,
      });
    } else {
      // 上拉事件监听
      this.setData({
        showSearch: true,
      });
    }
    this.setData({
      lastScrollTop: e.scrollTop,
    });
  },
  /**
   * 弹出层展示
   */
  showPopup(event) {
    const obj = event.currentTarget.dataset.obj;
    console.log("writeType:" + obj.type);
    this.setData({
      writeObj: obj,
      showPop: true,
      showSearch: false,
    });
  },
  showCreatPop() {
    this.setData({
      showCreatPop: true,
      showSearch: false,
    });
  },
  /**
   * 上传照片
   * @param {*} event
   */
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: "https://example.weixin.qq.com/upload", // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      formData: { user: "test" },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = this.data;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
      },
    });
  },
  /**
   * 新增对象
   * @param {*} e
   */
  onSubmit(e) {
    const formData = e.detail.value;
    switch (formData.type) {
      case "0":
        createObject({
          name: formData.name,
          type: Number(formData.type),
          desc: formData.desc,
        })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case "1":
        createObject({
          name: formData.name,
          type: Number(formData.type),
          desc: formData.desc,
          edges: {
            organization: {
              address: formData.address,
              type: formData.otype,
            },
          },
        })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case "2":
        createObject({
          name: formData.name,
          type: Number(formData.type),
          desc: formData.desc,
          edges: {
            course: {
              edges: {
                teacher: {
                  id: this.data.teachers.array[this.data.teachers.index].value,
                },
                organization: {
                  id: this.data.orgs.array[this.data.orgs.index].value,
                },
              },
            },
          },
        })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case "3":
        createObject({
          name: formData.name,
          type: Number(formData.type),
          desc: formData.desc,
        })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
    }
    onCreatClose();
  },
  /**
   * 弹出层关闭
   */
  onClose() {
    this.setData({
      showPop: false,
      showSearch: true,
    });
  },
  onCreatClose() {
    this.setData({
      showCreatPop: false,
      showSearch: true,
    });
  },
  selectType(event) {
    this.setData({
      selectType: event.detail,
    });
  },
  /**
   * 防止事件冒泡给父组件
   */
  stopPropagation() {
    // 什么都不做
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},
  onShow() {
    this.onSearch();
    getObjectsByTypeID(0).then((res) => {
      var teachers = {
        array: [],
        index: 0,
      };
      res.data.data.forEach((item) => {
        teachers.array.push({
          value: item.id,
          name: item.name,
        });
      });
      this.setData({
        teachers: teachers,
      });
    });
    getObjectsByTypeID(1).then((res) => {
      var orgs = {
        array: [],
        index: 0,
      };
      res.data.data.forEach((item) => {
        orgs.array.push({
          value: item.id,
          name: item.name,
        });
      });
      this.setData({
        orgs: orgs,
      });
    });
  },
  /**
   * 选择器改变Handler
   */
  bindPickerChange(e) {
    if (e.target.dataset.id == "teacher") {
      this.setData({
        "teachers.index": e.detail.value,
      });
    } else {
      this.setData({
        "orgs.index": e.detail.value,
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      reviewList: [],
      "requestPage.page": 1,
    });
    this.onSearch();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.onSearch();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
